home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11613 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  65 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: 76623,2065@compuserve.com  (Bobby Martin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Virtual Base Class
  5. Date: 15 Mar 1996 13:48:55 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4ibsg7$ahc@dub-news-svc-3.compuserve.com>
  8. References: <313F98D0.102E@ucla.edu> <4i1k92$3n8@apoll.informatik.uni-bonn.de> <31472DB0.511A@ucla.edu>
  9. Reply-To: 76623,2065@compuserve.com (Bobby Martin)
  10. NNTP-Posting-Host: ad09-038.compuserve.com
  11. X-Newsreader: IBM NewsReader/2 v1.03
  12.  
  13. >Roland Schregle wrote:
  14. >> 
  15. >> 
  16. >> I have the same problem! Somebody suggested the following (in terms of the
  17. >> above egg sample):
  18. >> 
  19. >> void f()
  20. >> {
  21. >>    a a1;
  22. >>    d* pd = (d*)(void*)&a1;
  23. >> }
  24. >> 
  25. >> I haven't tried this yet. C'mon you C++ cracks out there!!! :)
  26. >> 
  27. >> GanjaTron
  28.  
  29. This is a BAD way to try to solve this problem.  If you need to cast down
  30. from class a to class d, you have some problem in your design.  Maybe there 
  31. should be some virtual method declared in class a that can be overloaded in
  32. class d to call the method in which the conversion is currently being done,
  33. (thus eliminating the need for the conversion since you always call it with an
  34. object of class d) or maybe you have a list of class a's that should be broken
  35. up into a list of class a's and a list of class d's.
  36.  
  37. Anyway, a fairly nice solution to the problem in code is to put a dCast method
  38. in a, like this:
  39.  
  40. class d;
  41.  
  42. class a
  43.     {
  44. ..
  45.     virtual d* dCast() {return 0;}
  46. ..
  47.     };
  48.  
  49. (note that you'll need to put a forward reference to d (i.e. class d;) before
  50. your declaration of a.)
  51. Then redefine dCast in class d like this:
  52.  
  53. class d
  54.     {
  55. ..
  56.     virtual d* dCast() {return this;}
  57. ..
  58.     };
  59.  
  60. then use a1->dCast() wherever you might otherwise use (d*)a1.
  61.  
  62. Hope this helps!
  63.  
  64. Bobby Martin
  65.